package com.party.business.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.annotations.VisibleForTesting;
import com.hbga.xunpay.model.ChannelTransparentResModel;
import com.hbga.xunpay.model.PayOrderQueryResModel;
import com.party.business.domain.*;
import com.party.business.service.*;
import com.party.common.annotation.Anonymous;
import com.party.common.annotation.Log;
import com.party.common.core.controller.BaseController;
import com.party.common.core.domain.AjaxResult;
import com.party.common.core.domain.entity.SysRole;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.core.page.TableDataInfo;
import com.party.common.enums.BusinessType;
import com.party.common.exception.ServiceException;
import com.party.common.utils.*;
import com.party.course.domain.*;
import com.party.course.mapper.AmountInfoMapper;
import com.party.course.mapper.CoachInfoMapper;
import com.party.course.mapper.PlanClassMapper;
import com.party.course.mapper.StudentInfoMapper;
import com.party.course.service.IAmountInfoService;
import com.party.course.service.IPayReqInfoService;
import com.party.system.domain.SysConfig;
import com.party.system.mapper.SysRoleMapper;
import com.party.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 小程序接口
 */
@RestController
@RequestMapping("/webApi")
public class TWebApiController extends BaseController {
    //
    @Autowired
    private ITLbImageService tLbImageService;

    //
    @Autowired
    private ISysUserService sysUserService;
    //
//
    @Autowired
    private IKcTypeService kcTypeService;
    //
//
    @Autowired
    private ITTwxxService tTwxxService;
//


    @Autowired
    private IZqTypeService zqTypeService;


    @Autowired
    private IKcService kcService;


    @Autowired
    private ITSearchHisService tSearchHisService;

    @Autowired
    private ITCommentService tCommentService;

    @Autowired
    private ITOrderService tOrderService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ITScService tScService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private CoachInfoMapper coachInfoMapper;
    @Autowired
    private StudentInfoMapper studentInfoMapper;
    @Autowired
    private AmountInfoMapper amountInfoMapper;
    @Autowired
    private IPayReqInfoService payReqInfoService;


    /**
     * 保存用户的搜索记录
     */
    @PostMapping("searchHis/add")
    public AjaxResult searchHisAdd(@RequestBody TSearchHis tSearchHis) {
        tSearchHis.setContent(tSearchHis.getContent());
        tSearchHis.setUserId(getUserId() + "");
        return toAjax(tSearchHisService.save(tSearchHis));
    }


    /**
     * 删除用户的搜索记录
     */
    @PostMapping("searchHis/deleteAll")
    public AjaxResult searchHisdeleteAll() {
        QueryWrapper<TSearchHis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", getUserId());
        tSearchHisService.remove(queryWrapper);
        return AjaxResult.success();
    }


    /**
     * 删除某一个用户的搜索记录
     */
    @DeleteMapping("searchHis/{ids}")
    public AjaxResult searchHisremove(@PathVariable String[] ids) {
        return toAjax(tSearchHisService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 用户的搜索记录
     */

    @GetMapping("/searchHisList")
    public AjaxResult searchHisList(TSearchHis tSearchHis) {
        // 查询最近三天的
        PageUtils.startPage(1, 20);
        tSearchHis.setUserId(SecurityUtils.getUserIdStr());
        List<TSearchHis> list = tSearchHisService.selectTSearchHisList(tSearchHis);
        return AjaxResult.success(list);
    }

//

    /**
     * 注册协议和隐私政策  关于我们
     */
    @GetMapping("/nologin/twxxlist")
    public AjaxResult twxxlist(TTwxx tTwxx) {
        List<TTwxx> list = tTwxxService.selectTTwxxList(tTwxx);
        return AjaxResult.success(list);
    }

    /**
     * 轮播图列表
     */
    @GetMapping("/nologin/getLbImageList")
    public AjaxResult getLbImageList(TLbImage tLbImage) {
        List<TLbImage> list = tLbImageService.selectTLbImageList(tLbImage);
        return AjaxResult.success(list);
    }

    /**
     * 课程类型列表
     */
    @GetMapping("/nologin/getKcTypeList")
    public AjaxResult getKcTypeList(KcType kcType) {
        List<KcType> kcTypes = kcTypeService.selectKcTypeList(kcType);
        return AjaxResult.success(kcTypes);
    }


    /**
     * 专区类型列表
     */
    @GetMapping("/nologin/getZqTypeList")
    public AjaxResult getZqTypeList(ZqType zqType) {
        List<ZqType> zqTypes = zqTypeService.selectZqTypeList(zqType);
        return AjaxResult.success(zqTypes);
    }

    /**
     * 用户个人信息
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserByIdApp(userId);
        List<SysRole> roles = sysRoleMapper.selectRolesByUserId(sysUser.getUserId());
        if (roles != null && roles.size() > 0) {
            for (SysRole role : roles) {
                if ("教练".equals(role.getRoleName())  ||  "学管师".equals(role.getRoleName())) {
                    CoachInfo coachInfo = coachInfoMapper.findByUserId(userId.toString());
                    if(coachInfo!=null){
                        sysUser.setCoachId(coachInfo.getId());
                        sysUser.setRoleType(coachInfo.getRoleType());
                    }

                }
            }
        }
        return AjaxResult.success(sysUser);
    }



    /**
     * 用户个人信息（通过Id）
     */
    @GetMapping("/nologin/getUserInfoByUserId")
    public AjaxResult getUserInfoByUserId(String userId) {
        SysUser sysUser = sysUserService.selectUserById(Long.valueOf(userId));
        return AjaxResult.success(sysUser);
    }

    /**
     * 课程列表
     */
    @GetMapping("/nologin/kclist")
    public TableDataInfo kclist(Kc kc) {
        startPage();
        kc.setStatus("1");
        List<Kc> list = kcService.selectKcListApp(kc);
        return getDataTable(list);
    }

    /**
     * 课程详情
     */
    @Anonymous
    @GetMapping(value = "/kcDetail/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        Kc kc = new Kc();
        kc.setId(id);
        if (SecurityUtils.isLogin()) {
            kc.setUserId(SecurityUtils.getUserIdStr());
        }
        Kc kc1 = kcService.selectKcByIdApp(kc);
        if (kc1 == null) {
            throw new ServiceException("课程已删除");
        }
        if ("1".equals(kc1.getDelFlag())) {
            throw new ServiceException("课程已删除");
        }
        return AjaxResult.success(kc1);
    }


    /**
     * 课程购买记录
     */
    @GetMapping("/nologin/kcOrderFinishList")
    public TableDataInfo kcOrderFinishList(TOrder tOrder) {
        startPage();
        List<TOrder> list = tOrderService.selectTOrderListApp(tOrder);
        return getDataTable(list);
    }

    /**
     * 我的----------------收藏列表
     */
    @GetMapping("/mysckclist")
    public TableDataInfo mysckclist() {
        startPage();
        Kc kc = new Kc();
        kc.setUserId(SecurityUtils.getUserIdStr());
        List<Kc> list = kcService.selectKcListScApp(kc);
        return getDataTable(list);
    }

    /**
     * 取消收藏--传入课程Id
     */
    @PostMapping("/cancleScKc")
    public AjaxResult cancleScKc(@RequestBody Kc kc) {
        String kcId = kc.getId();
        if (StringUtils.isEmpty(kcId)) {
            return AjaxResult.error("课程id不能为空");
        }
        //根据 businessId 和 userId 删除 TSc
        QueryWrapper<TSc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id", kcId);
        queryWrapper.eq("user_id", SecurityUtils.getUserIdStr());
        tScService.remove(queryWrapper);
        return AjaxResult.success();
    }

    /**
     * 收藏--传入课程Id
     */
    @PostMapping("/addKcSc")
    public AjaxResult addKcSc(@RequestBody Kc kc) {
        String kcId = kc.getId();
        if (StringUtils.isEmpty(kcId)) {
            return AjaxResult.error("课程id不能为空");
        }
        // 先判断是否收藏过
        QueryWrapper<TSc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id", kcId);
        queryWrapper.eq("user_id", SecurityUtils.getUserIdStr());
        if (tScService.count(queryWrapper) > 0) {
            return AjaxResult.error("已收藏");
        }
        //根据 businessId 和 userId 删除 TSc
        TSc tSc = new TSc();
        tSc.setUserId(SecurityUtils.getUserIdStr());
        tSc.setBusinessId(kcId);
        tScService.save(tSc);
        return AjaxResult.success();
    }

    /**
     * 客服电话   客服微信号
     */
    @GetMapping("/nologin/getxtpzList")
    public AjaxResult getxtpzList() {
        SysConfig sysConfig = new SysConfig();
        List<SysConfig> sysConfigs = configService.selectConfigList(sysConfig);
        return AjaxResult.success(sysConfigs);
    }


    /**
     * 我的订单
     */
    @GetMapping("/myOrderList")
    public TableDataInfo myOrderList(TOrder order) {
        startPage();
        if (StrUtil.isEmpty(order.getProductId())) {
            order.setUserId(SecurityUtils.getUserIdStr());
        }
        List<TOrder> tOrders = tOrderService.selectTOrderListApp(order);
        for (TOrder tOrder : tOrders) {
            // 判断是否评价
            QueryWrapper<TComment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", tOrder.getId());
            queryWrapper.eq("user_id", SecurityUtils.getUserIdStr());
            long count = tCommentService.count(queryWrapper);
            tOrder.setIsFj(count > 0 ? 1 : 0);
            StudentInfo studentInfo = studentInfoMapper.findByOrderCode(tOrder.getOrderNo());
            if (studentInfo!=null  &&  StrUtil.isNotEmpty(studentInfo.getCoachId())) {
                CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(studentInfo.getCoachId());
                if (ObjectUtil.isNotEmpty(coachInfo)) {
                    studentInfo.setCoachPhone(coachInfo.getPhone());
                }
            }
            tOrder.setStudentInfo(studentInfo);
        }
        return getDataTable(tOrders);
    }

    @Resource
    private PlanClassMapper planClassMapper;
    /**
     * 我的订单
     */
    @GetMapping("/myOrderListKc")
    public TableDataInfo myOrderListKc(TOrder order) {
        startPage();
        if (StrUtil.isEmpty(order.getProductId())) {
            order.setUserId(SecurityUtils.getUserIdStr());
        }
        List<TOrder> tOrders = tOrderService.selectTOrderListKcApp(order);
        for (TOrder tOrder : tOrders) {
            // 判断是否评价
            QueryWrapper<TComment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", tOrder.getId());
            queryWrapper.eq("user_id", SecurityUtils.getUserIdStr());
            long count = tCommentService.count(queryWrapper);
            tOrder.setIsFj(count > 0 ? 1 : 0);
            StudentInfo studentInfo = studentInfoMapper.findByOrderCode(tOrder.getOrderNo());
            if (studentInfo!=null  &&  StrUtil.isNotEmpty(studentInfo.getCoachId())) {
                CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(studentInfo.getCoachId());
                if (ObjectUtil.isNotEmpty(coachInfo)) {
                    studentInfo.setCoachPhone(coachInfo.getPhone());
                }
            }
            tOrder.setStudentInfo(studentInfo);
            String planId = tOrder.getPlanId();
            if (StrUtil.isNotEmpty(planId)) {
                PlanClass planClass = planClassMapper.selectplanClassById(planId);
                if (ObjectUtil.isNotEmpty(planClass)) {
                    tOrder.setPlanClass(planClass);
                }
            }
        }
        return getDataTable(tOrders);
    }

//

//
//

//
//
//    @Autowired
//    private ITKcService tKcService;
//
//
//    /**
//     * 课程列表
//     */
//    @GetMapping("/getKcList")
//    public TableDataInfo getKcList(TKc kc) {
//        startPage();
//        List<TKc> tKcs = tKcService.selectTKcListApp(kc);
//        return getDataTable(tKcs);
//    }
//
//
//    /**
//     * 课程详情
//     */
//    @GetMapping(value = "/getkcDetail/{id}")
//    public AjaxResult getkcDetail(@PathVariable("id") String id) {
//        return AjaxResult.success(tKcService.selectTKcById(id));
//    }
//


    /**
     * 用户个人信息--修改
     */
    @PutMapping("updateUser")
    public AjaxResult updateUser(@RequestBody SysUser user) {
        user.setUpdateBy(getUsername());
        user.setUserId(SecurityUtils.getUserId());
        return toAjax(sysUserService.updateUserApp(user));
    }
//
//    /**
//     * 用户个人信息--用户注销
//     */
//    @DeleteMapping("/removeUser")
//    public AjaxResult removeUser() {
//        String username = SecurityUtils.getUsername();
//        if ("admin".equals(username)) {
//            return AjaxResult.error("超级管理员不能注销");
//        }
//        Long[] userIds = {SecurityUtils.getUserId()};
//        return toAjax(userService.deleteUserAppByIds(userIds));
//    }

    @Anonymous
    @PostMapping("/callbackPay")
    public String callbackPay(@RequestBody PayOrderQueryResModel model) {
        return tOrderService.callbackPay(model);
    }

    @Anonymous
    @RequestMapping("/callbackTransparent")
    @Transactional
    public String callbackTransparent(@RequestBody ChannelTransparentResModel model) {
        try {
            String result = "";
            PayReqInfo reqInfo = PayReqInfo.builder()
                    .id(IdUtil.simpleUUID())
                    .orderNo(model.getMchTransparentNo())
                    .payOrderId(model.getTransparentId())
                    .reqUrl("/kcsm/webApi/callbackTransparent")
                    .type("8")
                    .param("回调参数：" + JSON.toJSONString(model))
                    .build();
            AmountInfo amountInfo = amountInfoMapper.selectAmountInfoById(model.getMchTransparentNo());
            if (ObjectUtil.isNotEmpty(amountInfo)) {
                SysUser user = sysUserService.selectUserById(Long.parseLong(amountInfo.getUserId()));
                if (ObjectUtil.isNotEmpty(user)) {
                    BigDecimal amount = user.getAmount();
                    String encodeAll = URLUtil.decode(model.getRes());
                    PaymentResultVO paymentResultVO = JSONObject.parseObject(encodeAll, PaymentResultVO.class);
                    BigDecimal changeAmount = paymentResultVO.getDebitAmount();
                    //提现审批通过-我的余额减去提现金额
                    BigDecimal totalAmount = amount.subtract(changeAmount);
                    user.setAmount(totalAmount);
                    user.setUpdateTime(DateUtil.date());
                    sysUserService.updateUser(user);
                    //提现申请
                    amountInfo.setCashStatus("1");
                    amountInfo.setValidTime(DateUtil.now());
                    amountInfo.setAmount(amount);
                    amountInfo.setUpdateTime(DateUtil.date());
                    amountInfoMapper.updateById(amountInfo);
                    result = "success";
                }
            }else {
                result = "error";
            }
            reqInfo.setRepData(result);
            payReqInfoService.add(reqInfo);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}
